import request from '@/utils/request'
import { SAVE_USER, SAVE_PROFILE } from '@/store/actionTypes/profile'
/**
 * 获取用户信息
 * @returns
 */
export const getUser = () => {
  return async (dispatch) => {
    const { data: res } = await request({
      method: 'GET',
      url: '/user',
    })
    dispatch(saveUser(res))
  }
}

/**
 * 保存用户信息
 * @param {*} payload
 * @returns
 */
export const saveUser = (payload) => {
  return {
    type: SAVE_USER,
    payload,
  }
}

/**
 * 获取用户个人资料
 * @returns
 */
export const getProfile = () => {
  return async (dispatch) => {
    const { data: res } = await request({
      method: 'GET',
      url: '/user/profile',
    })
    dispatch(saveProfile(res))
  }
}

/**
 * 保存用户信息信息
 * @param {*} payload
 * @returns
 */
export const saveProfile = (payload) => {
  return {
    type: SAVE_PROFILE,
    payload,
  }
}

/**
 * 修改用户信息
 * @param {*} data
 * @returns
 */
export const editProfile = (data) => {
  return async (dispatch) => {
    await request({
      method: 'PATCH',
      url: '/user/profile',
      data,
    })
    dispatch(getProfile())
  }
}

/**
 * 修改头像
 * @param {*} fd
 * @returns
 */
export const updataPhoto = (fd) => {
  return async (dispatch) => {
    await request.patch('/user/photo', fd)
    dispatch(getProfile())
  }
}
